package manager

import (
	"barge/pkg/util"
	"github.com/spf13/viper"
)

const (
	TypePassword = "password"
	ActionBase64 = "base64"
)

func init() {
	ActionInfoManager.RegisterActionInfo(&ActionInfo{
		Name:     ActionBase64,
		Type:     TypePassword,
		Discript: "自动解析base64密码",
	})
}

type PasswordAction interface {
	Action(s *Password)
}

type PasswordAct func(s *Password)

func (a PasswordAct) Action(s *Password) {
	a(s)
}

type Password struct {
	Raw string `toml:"raw,omitempty"`
	Aes string `toml:"aes,omitempty"`
}

func (p *Password) EncodeAes() error {
	if p.Aes != "" || p.Raw == "" {
		return nil
	}
	key := viper.GetString("sys.aesKey")
	aes, err := util.EncryptAES(key, p.Raw)
	if err != nil {
		return err
	}
	p.Aes = aes
	return nil
}

func (p *Password) DecodeAes() error {
	if p.Raw != "" || p.Aes == "" {
		return nil
	}
	key := viper.GetString("sys.aesKey")
	decodePassword, err := util.DecryptAES(key, p.Aes)
	if err != nil {
		return err
	}
	p.Raw = decodePassword
	return nil
}

func (p *Password) Action(rules []*Rule) {
	for _, rule := range rules {
		a := rule.AsPasswordAction()
		if a != nil {
			a.Action(p)
		}
	}
}
